package org.zjsru.user.service;

import org.zjsru.user.mapper.UserMapper;
import org.zjsru.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User queryById(Long id) {
        return userMapper.findById(id);
    }

    public User register(User user) {
        // 1. 对密码进行加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);
        
        // 2. 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        
        // 3. 保存用户
        userMapper.insert(user);
        
        // 4. 返回用户信息（不包含密码）
        user.setPassword(null);
        return user;
    }

    public User login(String username, String password) {
        // 1. 根据用户名查询用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        
        // 2. 对输入的密码进行加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        
        // 3. 比较密码
        if (!user.getPassword().equals(encryptedPassword)) {
            throw new RuntimeException("密码错误");
        }
        
        // 4. 返回用户信息（不包含密码）
        user.setPassword(null);
        return user;
    }
}